﻿using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Primitives;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Microsoft.AspNetCore.Http
{
    public static class HttpContextExtension
    {
        public static string GetContextParameter(this HttpContext httpContext, string parameterName)
        {
            var value = TryGetValue(() => httpContext.Request.Query[GetRequestKey(httpContext.Request.Query.Keys, parameterName)]);

            if (string.IsNullOrWhiteSpace(value))
            {
                value = TryGetValue(() => httpContext.Request.Form[GetRequestKey(httpContext.Request.Form.Keys, parameterName)]);
            }
            if (string.IsNullOrWhiteSpace(value))
            {
                value = TryGetValue(() => httpContext.Request.Headers[GetRequestKey(httpContext.Request.Headers.Keys, parameterName)].ToString());
            }
            return value;
        }

        private static string TryGetValue(Func<StringValues> getter)
        {
            try
            {
                var value =  getter?.Invoke();
                return value.Equals(null) ? null : value;
            }
            catch (Exception)
            {
                return null;
            }
        }
        private static string GetRequestKey(IEnumerable<string> keys, string parameterName)
        {
            return keys.FirstOrDefault(key => key.ToLower() == parameterName.ToLower())??string.Empty;
        }
    }
}
